/*
 * (C) Copyright 2005-2010 by Burrp Software Pvt. Ltd. All Rights Reserved.
 *
 * This software is the proprietary information of Burrp Software Pvt. Ltd.
 * Use is subject to license terms.
 *
 * Burrp Software Pvt. Ltd. -- http://www.burrp.com
 */
package com.showmemysite.rules;
import org.htmlparser.*;
import org.htmlparser.lexer.Lexer;
import org.htmlparser.tags.*;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

public class StripLinks {
	public static String customUrl;
	public static String coreUrl = "http://showmemysite.appspot.com/Program?link=";
//	public static String script1 = " <script type=\"text/javascript\" src=\"/js/cursor.js\"></script>";
//	public static String script2 = " <script type=\"text/javascript\" src=\"/js/squiggle.js\"></script>";
	public static ScriptTag script1 = new ScriptTag();
	public static ScriptTag script2 = new ScriptTag();
	static{
	script1.setAttribute("src", "http://showmemysite.appspot.com/js/squiggle.js");
	script2.setAttribute("src", "http://showmemysite.appspot.com/js/cursor.js");
	}

	public static String stripLinks(String content, String baseUrl){
		StringBuilder pageContent = new StringBuilder();
		customUrl = baseUrl;
		try{
			Parser parser = new Parser(content);
			Lexer lexer = parser.getLexer();
			Node node = lexer.nextNode();
			while(node != null){
				processNodes(node);
				pageContent.append(node.toHtml());
				node = lexer.nextNode();
			}
		}catch(ParserException pe){
			return content;
		}
		return pageContent.toString();

	}

	private static void processNodes(Node node){
		if(node instanceof LinkTag){
			LinkTag link = (LinkTag)node;
			link.setLink(encryptLink(link.getLink()));
		}
		if(node instanceof ImageTag){
			ImageTag img = (ImageTag)node;
			img.setImageURL(sanitizeImageUrl(img.getImageURL()));
		}
		if(node instanceof ScriptTag){
			ScriptTag script = (ScriptTag)node;
			//TODO:
		}
		if(node instanceof HeadTag){
			HeadTag head = (HeadTag)node;
			NodeList list = head.getChildren();
			if(list == null){
				list = new NodeList();
			}
			list.add(script1);
			list.add(script2);
			head.setChildren(list);
		}
//		if(node instanceof BodyTag){
//			BodyTag body = (BodyTag)node;
//			body.setAttribute("onload", "draw();");
//		}
		if(node.getChildren() != null)
		for(Node childNode:node.getChildren().toNodeArray()){
			processNodes(childNode);
		}
	}

	private static String encryptLink(String link){
		if(link.startsWith("http://")){
			link = coreUrl + link;
		}else if(link.startsWith("/")){
			link = coreUrl + customUrl+link;
		}
		return link;
	}
	
	private static String sanitizeImageUrl(String link){
		if(link.startsWith("/")){
			return customUrl+link;
		}
		return link;
	}
}
